<template>
  <el-form ref="formRef" :model="localForm" label-width="120" :rules="rules">
    <el-form-item prop="courseId" label="课程ID">
      <el-input v-model="localForm.courseId" placeholder="请输入课程ID" />
    </el-form-item>
    <el-form-item prop="courseName" label="课程名称">
      <el-input v-model="localForm.courseName" placeholder="请输入课程名称" />
    </el-form-item>
    <el-form-item prop="courseType" label="课程类型">
      <el-input v-model="localForm.courseType" placeholder="请输入课程类型" />
    </el-form-item>
    <el-form-item prop="level" label="课程级别">
      <el-input v-model="localForm.level" placeholder="请输入课程级别" />
    </el-form-item>
    <el-form-item prop="description" label="课程简介">
      <el-input v-model="localForm.description" placeholder="请输入课程简介" />
    </el-form-item>
    <el-form-item prop="totalHours" label="总课时">
      <el-input-number v-model="localForm.totalHours" :min="0" />
    </el-form-item>
    <el-form-item prop="classroom" label="教室">
      <el-input v-model="localForm.classroom" placeholder="请输入教室" />
    </el-form-item>
    <el-form-item prop="maxStudents" label="最大学员数">
      <el-input-number v-model="localForm.maxStudents" :min="0" />
    </el-form-item>
    <el-form-item prop="currentStudents" label="已报学员数">
      <el-input-number v-model="localForm.currentStudents" :min="0" />
    </el-form-item>
    <el-form-item prop="status" label="状态">
      <el-select v-model="localForm.status" placeholder="请选择状态">
        <el-option :value="true" label="开课中" />
        <el-option :value="false" label="已下架" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const props = defineProps(['courseFormData', 'drawerTitle'])
const emit = defineEmits(['save', 'cancel'])

const formRef = ref()
const localForm = reactive({})

// 监听 courseFormData，决定是编辑还是添加
watch(
  () => props.courseFormData,
  (val) => {
    if (!val) return
    // 清空 localForm
    Object.keys(localForm).forEach(key => delete localForm[key])
    // 赋值
    Object.assign(localForm, val)
  },
  { immediate: true }
)

// 校验规则
const rules = reactive({
  courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }]
})

// 保存
const onSave = () => {
  formRef.value.validate().then(() => {
    ElMessageBox.confirm(
      `确定要${props.drawerTitle}吗?`,
      '提示',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    ).then(() => {
      emit('save', { ...localForm })
      // 不要在这里弹 ElMessage.success
    })
  })
}

// 取消
const onCancel = () => {
  emit('cancel')
}
</script>

<style lang="less" scoped>
.el-form-item {
  margin-bottom: 16px;
}
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
.el-button {
  margin-right: 10px;
}
</style>